package com.bwie.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.utils.Result;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/5/21 13:45
 */

@RestController
@RequestMapping("/user/index")
@Slf4j
public class IndexController {

    @Autowired
    HttpServletRequest request;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TbUserService tbUserService;

    @PostMapping("/login")
    public Result login(@RequestBody @Validated LoginVo loginVo){
        //--1 判断用户是否存在
        TbUser tbUser = tbUserService.getOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if(tbUser == null) {
            return Result.error().setMsg("用户不存在");
        }

        //--2 判断密码是否正确
        // md5加密的密码，需要比较加密后的字符串（对比密文）
        String hash = DigestUtil.md5Hex(loginVo.getUserPass());
        log.info("加密的密码：" + hash);
        if(!hash.equals(tbUser.getUserPass())) {
            return Result.error().setMsg("密码错误");
        }

        //--3 生成token并放入缓存
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName())
                .compact();
        String key = "token-" + tbUser.getUserId();
        // token过期时间，设置为60分钟
        stringRedisTemplate.opsForValue().set(key, token, 60, TimeUnit.MINUTES);

        //--4 返回用户信息以及token
        tbUser.setUserPass(null);
        tbUser.setToken(token);

        return Result.ok().setData(tbUser);
    }

    /**
     * @description 获取当前登录用户的菜单树
     * @params []
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/22 11:06
     */
    @PostMapping("/getMenuTree")
    public Result getMenuTree() {
        //--1 获取token，并获得用户ID
        String token = request.getHeader("token");
        if(token == null) {
            return Result.error().setMsg("请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        //--2 根据用户ID查询用户菜单树
        List<TbMenu> menuTree = tbUserService.getMenuTreeByUserId(userId);

        //--3 返回用户菜单树

        return Result.ok().setData(menuTree);
    }

    /**
     * @description 分页获取商户列表
     * @params []
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/22 14:03
     */
    @PostMapping("/getUserList")
    public Result getUserList(@RequestBody PageUserVo pageUserVo) {
        return tbUserService.getUserList(pageUserVo);
    }

    /**
     * @description 修改商户
     * @params []
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/22 15:51
     */
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody TbUser tbUser) {
        return tbUserService.updateUser(tbUser);
    }

    /**
     * @description 文件上传
     * @params [file]
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/22 16:29
     */
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestPart("file")MultipartFile file){
        return tbUserService.uploadFile(file);
    }

    /**
     * @description 根据ID删除商户
     * @params [userId]
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/23 10:13
     */
    @PostMapping("/deleteUserById/{userId}")
    public Result deleteUserById(@PathVariable("userId") Integer userId) {
        return tbUserService.deleteUserById(userId);
    }

    /**
     * @description 批量删除商户
     * @params [userList]
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/23 10:29
     */
    @PostMapping("/deleteUserAll")
    public Result deleteUserAll(@RequestBody List<TbUser> userList) {
        return tbUserService.deleteUserAll(userList);
    }

    /**
     * @description 审核商户
     * @params [tbUser]
     * @return com.bwie.utils.Result
     * @author 军哥
     * @date 2025/5/23 11:23
     */
    @PostMapping("/checkUser")
    public Result checkUser(@RequestBody TbUser tbUser) {
        return tbUserService.checkUser(tbUser);
    }

}
